<template>
  <div class="app-container">
    <el-container>
      <!-- 左侧树 -->
      <el-aside width="500px">
        <div class="filter-container">
          <el-input v-model="filterText" placeholder="输入关键字进行过滤" style="width:200px;padding-right:10px;" />
          <el-button type="primary" size="mini" icon="el-icon-search" @click="refreshTree">
            刷新
          </el-button>
          <el-button type="warning" size="mini" icon="el-icon-upload" @click="handleUpload">
            导入
          </el-button>
          <el-button :loading="fileDownLoading" type="danger" size="mini" icon="el-icon-download" @click="handleDownload">
            导出
          </el-button>
        </div>
        <el-tree
          ref="tree"
          :props="treeProps"
          :indent="16"
          node-key="industryCode"
          :render-after-expand="true"
          :highlight-current="true"
          :check-on-click-node="true"
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          :lazy="true"
          :load="loadSubData"
          @node-click="handleNodeClick"
        />
      </el-aside>
      <el-main style="padding-top: 10px;">
        <div class="filter-container">
          <el-button v-if="viewTemp.industryName != ''" type="success" size="mini" @click="handleAddSub(viewTemp)">
            新增下级
          </el-button>
          <el-button v-if="viewTemp.pCode != ''" type="success" size="mini" @click="handleAddSibling(viewTemp)">
            新增同级
          </el-button>
          <el-button v-if="viewTemp.industryCode != ''" type="warning" size="mini" @click="handleUpdate(viewTemp)">
            编辑
          </el-button>
          <el-button v-if="viewTemp.industryCode != '' && viewTemp.isLeaf" size="mini" type="danger" @click="handleDelete(viewTemp)">
            删除
          </el-button>
        </div>
        <el-form :model="viewTemp" :disabled="true" label-position="right" label-width="150px" style="width: 500px; margin-left:50px;">
          <el-form-item label="经济行业分类代码" prop="industryCode">
            <el-input v-model="viewTemp.industryCode" />
          </el-form-item>
          <el-form-item label="经济行业分类名称" prop="industryName">
            <el-input v-model="viewTemp.industryName" />
          </el-form-item>
          <el-form-item label="上级行业编码" prop="pCode">
            <el-input v-model="viewTemp.pCode" />
          </el-form-item>
          <el-form-item label="备注说明" prop="industryDesc">
            <el-input v-model="viewTemp.industryDesc" autosize type="textarea" :rows="3" />
          </el-form-item>
        </el-form>
      </el-main>
    </el-container>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="550px" :close-on-click-modal="false" :close-on-press-escape="false" center>
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="150px" class="form-center">
        <el-form-item label="经济行业分类代码" prop="industryCode">
          <el-input v-model="temp.industryCode" maxlength="8" :disabled="dialogStatus==='update'" />
        </el-form-item>
        <el-form-item label="经济行业分类名称" prop="industryName">
          <el-input v-model="temp.industryName" maxlength="64" />
        </el-form-item>
        <el-form-item label="上级行业编码" prop="industryPCode">
          <el-input v-model="temp.pCode" :disabled="true" />
        </el-form-item>
        <el-form-item label="备注说明" prop="industryDesc">
          <el-input v-model="temp.industryDesc" autosize type="textarea" :rows="3" maxlength="320" show-word-limit />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="批量导入国民经济行业分类信息数据"
      :visible.sync="uploadExcelDialogVisible"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      center
    >
      <div class="app-container">
        <el-upload
          ref="upload"
          action="customized"
          :limit="1"
          accept=".xls,.xlsx"
          :http-request="handleExcelUpload"
          :auto-upload="false"
        >
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <el-button :loading="fileUploading" style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
          <el-button :loading="fileDownLoading" style="margin-left: 10px;" size="small" type="info" @click="handleDownloadTemplate">下载模板</el-button>
          <div slot="tip" class="el-upload__tip">只能上传xls/xlsx文件</div>
        </el-upload>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { fetchList, createDictIndustry, updateDictIndustry, deleteDictIndustry, importDictIndustry, exportDictIndustry, exportDictIndustryTemplate } from '@/api/base/dict/dictIndustry'
import { saveRespExcel } from '@/utils'

export default {
  name: 'DictIndustry',
  data() {
    return {
      treeProps: {
        label: 'industryName',
        isLeaf: 'leaf'
      },
      fileDownLoading: false,
      fileUploading: false,
      viewTemp: {
        industryCode: '',
        industryName: '',
        pCode: '',
        industryDesc: '',
        createAt: '',
        createBy: '',
        updateAt: '',
        updateBy: ''
      },
      temp: {
        industryCode: '',
        industryName: '',
        pCode: '',
        industryDesc: '',
        createAt: '',
        createBy: '',
        updateAt: '',
        updateBy: ''
      },
      filterText: '',
      dialogFormVisible: false,
      uploadExcelDialogVisible: false,
      industryTreeDemoVisible: false,
      industryComboboxDemoVisible: false,
      industryCascaderDemoVisible: false,
      dialogStatus: '',
      textMap: {
        update: '更新国民经济行业分类信息',
        create: '新增国民经济行业分类信息'
      },
      rules: {
        industryCode: [{ required: true, message: '经济行业分类代码不能为空', trigger: 'change' },
          { max: 8, message: '经济行业分类代码长度不能大于8个字符', trigger: 'change' }],
        industryName: [{ required: true, message: '经济行业分类名称不能为空', trigger: 'change' },
          { max: 64, message: '经济行业分类名称长度不能大于64个字符', trigger: 'change' }],
        pCode: [{ required: true, message: '上级行业编码不能为空', trigger: 'change' },
          { max: 8, message: '上级行业编码长度不能大于8个字符', trigger: 'change' }],
        industryDesc: [{ max: 320, message: '备注说明长度不能大于320个字符', trigger: 'change' }]
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  methods: {
    loadSubData(node, resolve) {
      if (node.level === 0) {
        return resolve([{
          industryCode: '',
          industryName: '国民经济行业分类',
          pCode: '',
          leaf: false,
          children: []
        }])
      } else {
        fetchList(node.data.industryCode).then(response => {
          resolve(response.data)
        })
      }
    },
    handleNodeClick(data, node, other) {
      this.viewTemp.industryCode = data.industryCode
      this.viewTemp.industryName = data.industryName
      this.viewTemp.pCode = data.pCode
      this.viewTemp.industryDesc = data.industryDesc
      this.viewTemp.isLeaf = node.isLeaf
    },
    filterNode(value, data, node) {
      if (!value) {
        return true
      }
      return (data.industryName.indexOf(value) !== -1 || data.industryCode.indexOf(value) !== -1)
    },
    refreshTree() {
      // 本处使用了el-tree内部方法，存在升级危险
      const pNode = this.$refs.tree.getNode('')
      var theChildren = pNode.childNodes
      theChildren.splice(0, theChildren.length)
      pNode.loaded = false
      pNode.expanded = false
    },
    resetTemp() {
      this.temp = {
        industryCode: '',
        industryName: '',
        pCode: '',
        industryDesc: '',
        createAt: '',
        createBy: '',
        updateAt: '',
        updateBy: ''
      }
    },
    submitUpload() {
      this.$refs.upload.submit()
    },
    handleAddSub(row) {
      this.resetTemp()
      this.temp.pCode = row.industryCode
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleAddSibling(row) {
      this.resetTemp()
      this.temp.pCode = row.pCode
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createDictIndustry(this.temp).then((response) => {
            response.data.leaf = true
            const pNode = this.$refs.tree.getNode(this.temp.pCode)
            if (pNode) {
              this.$refs.tree.append(response.data, pNode)
              pNode.isLeaf = false
            }
            this.dialogFormVisible = false
            this.$message({
              message: '国民经济行业分类信息数据提交处理成功！',
              type: 'success'
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateDictIndustry(this.temp).then((response) => {
            const node = this.$refs.tree.getNode(this.temp.industryCode)
            if (node) {
              node.data.industryCode = this.temp.industryCode
              node.data.industryName = this.temp.industryName
              node.data.pCode = this.temp.pCode
              node.data.industryDesc = this.temp.industryDesc
            }
            if (this.viewTemp.industryCode === this.temp.industryCode) {
              this.viewTemp.industryName = this.temp.industryName
              this.viewTemp.pCode = this.temp.pCode
              this.viewTemp.industryDesc = this.temp.industryDesc
            }
            this.dialogFormVisible = false
            this.$message({
              message: '国民经济行业分类信息数据提交更新成功！',
              type: 'success'
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$msgbox({
        type: 'warning',
        title: '确认信息',
        message: '确认删除国民经济行业分类信息数据[' + row.industryCode + ']？',
        showCancelButton: true,
        showClose: false,
        closeOnPressEscape: false,
        closeOnClickModal: false,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            deleteDictIndustry(row.industryCode).then((response) => {
              const node = this.$refs.tree.getNode(row.industryCode)
              if (node) {
                this.$refs.tree.remove(node)
              }
              this.$message({
                message: '国民经济行业分类信息数据[' + row.industryCode + ']删除成功！',
                type: 'success'
              })
              done()
              instance.confirmButtonLoading = false
            }, (response) => {
              done()
              instance.confirmButtonLoading = false
            })
          } else {
            done()
          }
        }
      }).catch(() => {})
    },
    handleUpload() {
      this.uploadExcelDialogVisible = true
    },
    handleExcelUpload(file) {
      if (!file || !file.file) {
        return function() {
          Promise.resolve(file)
        }
      }
      this.fileUploading = true
      importDictIndustry(file).then(response => {
        this.refreshTree()
        this.$message({
          message: '国民经济行业分类信息文件导入处理成功！',
          type: 'success'
        })
        this.fileUploading = false
        this.uploadExcelDialogVisible = false
      }, (response) => {
        this.fileUploading = false
      })
    },
    handleDownload() {
      this.fileDownLoading = true
      exportDictIndustry(this.filterText).then(response => {
        saveRespExcel(response)
        this.fileDownLoading = false
      }, (response) => {
        this.fileDownLoading = false
      })
    },
    handleDownloadTemplate() {
      this.fileDownLoading = true
      exportDictIndustryTemplate().then(response => {
        saveRespExcel(response)
        this.fileDownLoading = false
      }, (response) => {
        this.fileDownLoading = false
      })
    }
  }
}
</script>
